<?php
/**
 * Created by PhpStorm.
 * User: chenzhitao
 * Date: 2018/5/9
 * Time: 下午6:49
 */

namespace App\Busi\Modules\Resource;


use App\Busi\Modules\BaseBusi;
use App\Busi\Traits\CategoryTrait;
use App\Busi\Traits\ConsultTrait;
use App\Busi\Traits\PolicyTrait;
use App\Busi\Traits\UserTrait;
use App\Exceptions\ErrorCode\UserError;
use App\Exceptions\UserException;
use App\Http\Requests\ConsultGetOneRo;
use App\Models\Consult;
use App\Models\Policy;

class ConsultGetOneBusi extends BaseBusi
{
    use UserTrait,PolicyTrait,ConsultTrait;
    public function handle(ConsultGetOneRo $ro){
        $id = $ro->id;
        $uid = $ro->uid;
        $user = $this->getUserByUid($uid);
        if(!$user){
            throw new UserException(UserError::USER_NOT_EXIST);
        }
        $userId = $user['id'];


        //获取该订单的详情

        $where = [
            ['id','=',$id],
            ['flag','=',1]
        ];
        $fields = ['supcategory_id','subcategory_id','address','phone','remark','is_view','created_at'];
        $data = Consult::where($where)->select($fields)->first();
        if($data['is_view'] == 0){
            $amount = $this->getUserAllAmountByUserId($userId);

            if($amount == 0){
                throw new UserException(UserError::AMOUNT_NOT_ENOUGH);
            }
            //获取用户所有的订单券,随机减1,优先减免费的
            $this->decreaseAmount($userId,1);
            $update = [
                "is_view"=>1,

            ];
            Consult::where("id",$id)->update($update);
        }
        $tmp['category_name'] = $this->getAllCategoryNameByID($data['subcategory_id']);
        $tmp['phone'] = $data['phone'];
        $tmp['address'] = $data['address'];
        $tmp['remark'] = $data['remark'];
        $tmp['create_time'] = substr($data['created_at'],0,10);
        return $tmp;

    }
}